package com.zg.autoflow.util;

import com.aspose.cells.Workbook;
import com.aspose.words.FontSettings;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.utils.OSinfo;
import com.utils.RT;
import com.zg.common.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.util.List;

@Slf4j
public class PdfUtils {




    /**
     * 合并PDF文件
     *
     * @param sourceFilePaths 需要合并的PDF文件路径列表
     * @param destFilePath    合并后的新文件
     */
    public static File mergePdfFile(List<File> sourceFilePaths, File destFilePath) {

        if (sourceFilePaths == null || sourceFilePaths.isEmpty() || destFilePath == null) {
            return null;
        }
        if (sourceFilePaths.size() == 0) {
            return null;
        }

        if (sourceFilePaths.size() == 1) {
            return sourceFilePaths.get(0);
        }

        com.itextpdf.text.Document document = null;
        PdfCopy copy = null;
        OutputStream os = null;
        try {

            os = new BufferedOutputStream(new FileOutputStream(destFilePath));
            document = new com.itextpdf.text.Document(new PdfReader(new FileInputStream(sourceFilePaths.get(0))).getPageSize(1));
            copy = new PdfCopy(document, os);
            document.open();
            for (File sourceFilePath : sourceFilePaths) {
                // 读取需要合并的PDF文件
                PdfReader reader = new PdfReader(new FileInputStream(sourceFilePath));
                // 获取PDF文件总页数
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (copy != null) {
                try {
                    copy.close();
                } catch (Exception ex) {
                    /* ignore */
                }
            }
            if (document != null) {
                try {
                    document.close();
                } catch (Exception ex) {
                    /* ignore */
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception ex) {
                    /* ignore */
                }
            }
        }
        return destFilePath;
    }

    public static File transExcelToPdf(File excelTempFile) {
        FileOutputStream fileOS = null;
        try {
            long old = System.currentTimeMillis();
            //判断是否windows系统，Linux要读取字体，否则pdf字体为方格
            if (!OSinfo.isWindows()) {
                FontSettings.getDefaultInstance().setFontsFolder("/usr/share/fonts/", true);
            }
            Workbook wb = new Workbook(excelTempFile.getAbsolutePath());// 原始excel路径
            File pdfFile = new File(RT.getRandomForWordInt(16) + ".pdf");// 输出路径
            fileOS = new FileOutputStream(pdfFile);
            com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
            pdfSaveOptions.setMergeAreas(true);
            //缩放到一个页面（如果列太多 太长）
            //pdfSaveOptions.setOnePagePerSheet(true);
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("读取excel并转pdf共耗时：" + ((now - old) / 1000.0) + "秒");

            try {
                fileOS.close();
            }catch (Exception e)
            {
            }

            if (excelTempFile.exists()) {
                excelTempFile.delete();
            }
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fileOS != null) {
                try {
                    fileOS.close();
                } catch (Exception e2) {
                }
            }
        }
    }

    /**
     * 将图片转换成pdf文件
     * imgFilePath 需要被转换的img所存放的位置。 例如imgFilePath="D:\\projectPath\\55555.jpg";
     * pdfFilePath 转换后的pdf所存放的位置 例如pdfFilePath="D:\\projectPath\\test.pdf";
     *
     * @return
     * @throws IOException
     */
    public static File imgToPdf(URL img) {
        try {
            return  imgToPdf(com.itextpdf.text.Image.getInstance(img));
        } catch (Exception e) {
            throw new BusinessException(-1, "生成pdf失败请重试");
        }
    }

    public static File imgToPdf(com.itextpdf.text.Image image) {

        String fileName = RT.getRandomForWordInt(16) + ".pdf";
        String tempFile = "tempFile/" + fileName;
        File file = new File(tempFile);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            PdfWriter.getInstance(document, fos);


            // 写入一段文字
            //document.add(new Paragraph("JUST TEST ..."));
            float imageHeight = image.getScaledHeight();
            float imageWidth = image.getScaledWidth();
            if(imageWidth>imageHeight)
            {
                // 设置文档的大小
                document.setPageSize(PageSize.A4.rotate());
//                image.setRotationDegrees(90);
                float t = imageHeight;
                imageHeight = imageWidth;
                imageWidth = t;
            }else
            {
                // 设置文档的大小
                document.setPageSize(PageSize.A4);
            }
            float sh = 800*100/imageHeight;
            float sw = 500*100/imageWidth;
            image.scalePercent(Math.min(sh,sw));
            image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);

            // 打开文档
            document.open();

            // 插入一个图片
            document.add(image);
        } catch (Exception de) {
            System.out.println(de.getMessage());
        } finally {
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (Exception e) {

            }
        }
        return  file;
    }
}
